package com.test.mchelepesa.activity_fragment_rice.login_rice;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.IntentSenderRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;

import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest;
import com.google.android.gms.auth.api.identity.Identity;
import com.test.mchelepesa.R;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseLoginActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseApplication_rice;
import com.test.mchelepesa.bean_rice.StaticConfig_rice;
import com.test.mchelepesa.bean_rice.config_info_rice.AppShowInfo_rice;
import com.test.mchelepesa.bean_rice.config_info_rice.GlobalConfig_rice;
import com.test.mchelepesa.bean_rice.user_info_rice.LoginInfo_rice;
import com.test.mchelepesa.constant_rice.Constant_rice;
import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.util_rice.analytics_rice.timezone_rice.TimeZoneHostEnum_rice;
import com.test.mchelepesa.util_rice.helper_rice.UserInfoHelper_rice;
import com.test.mchelepesa.util_rice.http_rice.HttpManager_rice;
import com.test.mchelepesa.view_rice.RiceEditText;
import com.test.mchelepesa.view_rice.widget_rice.SelectView_rice;
import com.test.mchelepesa.util_rice.analytics_rice.util_rice.AnalyticsUtil_rice;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.TimeZone;

public class LoginPhoneNumActivity_rice extends BaseLoginActivity_rice {

    private SelectView_rice countrySv;
    private TextView prefixTv;
    private RiceEditText phoneNumEt;

    private TextView mobileTitleTv;

    private ImageButton agreementIb;
    private TextView agreementTv;

    private boolean isAgree = true;

    private String privacyPath = "";

    private boolean phoneNumberHintFlag = true;

    private String prefix;

    private final ActivityResultLauncher<IntentSenderRequest> phoneNumberHintLauncher = registerForActivityResult(
            new ActivityResultContracts.StartIntentSenderForResult(),
            result -> {
                try {

                    String mobile = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.getData());

                    if (TextUtils.isEmpty(mobile)) return;

                    prefix = StringUtil_rice.getSafeString(prefix);

                    if (mobile.startsWith(prefix)) phoneNumEt.setText(mobile.replace(prefix,""));
                    else phoneNumEt.setText(mobile);

                } catch (Exception e) {
                    StringUtil_rice.printException(e);
                }
            }
    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_phone_num_rice);
        init();
    }

    @SuppressLint("SetTextI18n")
    private void init() {

        countrySv = findViewById(R.id.activity_login_phone_num_sv_country);
        prefixTv = findViewById(R.id.activity_login_phone_num_tv_prefix);
        phoneNumEt = findViewById(R.id.activity_login_phone_num_et_phone_num);
        mobileTitleTv = findViewById(R.id.activity_login_phone_num_tv_mobile_title);
        agreementIb = findViewById(R.id.activity_login_phone_num_ib_agreement);
        agreementTv = findViewById(R.id.activity_login_phone_num_tv_agreement);

        phoneNumEt.setBpType(getClass().getSimpleName()+"PHONE_NUMBER_INPUT");

        initLicense(
                findViewById(R.id.activity_login_view_license),
                findViewById(R.id.activity_login_license_logo),
                findViewById(R.id.activity_login_license_company_name)
        );

        agreementIb.setOnClickListener(v -> setAgree(!isAgree));

        ArrayList<String> countries = GlobalConfig_rice.getInstance().getCountries();
        ArrayList<String> countriesName = new ArrayList<>();

        phoneNumEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                //测试账号登录
                if (s.length()>=9 && isAgree){
                    String phoneNum = s.toString();
                    String accountToken = AppShowInfo_rice.getInstance().isTestAccount(phoneNum);
                    if (!TextUtils.isEmpty(accountToken)) {
                        UserInfoHelper_rice.getInstance().setMobile_rice(phoneNum);
                        try {
                            JSONObject object = new JSONObject();
                            object.put("token", accountToken);
                            object.put("userId", phoneNum);
                            object.put("typ", UserInfoHelper_rice.LOGIN_TYPE_OLD_rice);
                            LoginInfo_rice.parse(object);
                            onUserLoginResponse_rice();
                        } catch (Exception e) {
                            StringUtil_rice.printException(e);
                        }
                    }
                }
            }
        });

        phoneNumEt.addOnFocusChangeListener((v, hasFocus) -> {

            if (hasFocus && phoneNumberHintFlag){

                phoneNumberHintFlag = false;

                GetPhoneNumberHintIntentRequest request = GetPhoneNumberHintIntentRequest.builder().build();

                Identity.getSignInClient(this).getPhoneNumberHintIntent(request)
                        .addOnSuccessListener(result -> {
                            try {
                                phoneNumberHintLauncher.launch(new IntentSenderRequest.Builder(result.getIntentSender()).build());
                            } catch (Exception e) {
                                StringUtil_rice.printException(e);
                            }
                        })
                        .addOnFailureListener(e -> Log.e("=Login", "Phone number hint failed"));

            }

        });

        findViewById(R.id.activity_login_phone_num_btn_next).setOnClickListener(v -> {

            if (!isAgree){
                showToast_rice(getString(R.string.tips_agreement));
                return;
            }

            if (TextUtils.isEmpty(countrySv.getInput()) || TextUtils.isEmpty(phoneNumEt.getText())) {
                showToast_rice(getString(R.string.word_input_tip));
                return;
            }

            String phoneNum = StringUtil_rice.getSafeString(phoneNumEt.getText().toString());

            HttpManager_rice.getInstance().saveUserBuriedPointAndUpload(getClass().getSimpleName()+"_NEXT_CLICK",phoneNum);

            String accTk = AppShowInfo_rice.getInstance().isTestAccount(phoneNum);
            if (!TextUtils.isEmpty(accTk)){

                LoginInfo_rice.getInstance().sToken(accTk);
                LoginInfo_rice.getInstance().sUserId(phoneNum);
                UserInfoHelper_rice.getInstance().setMobile_rice(phoneNum);
                onUserLoginResponse_rice();
                return;
            }

            HttpManager_rice.getInstance().userLogin(phoneNum);

        });

        //国家选择初始化
        String timeZoneId = TimeZone.getDefault().getID();
        if (timeZoneId.equalsIgnoreCase(TimeZoneHostEnum_rice.TimeZoneTanzania.getTimeZoneId()) && countries.contains(Constant_rice.WordPrefix + Constant_rice.Suffix_Tanzania)) {
            selectCountry(Constant_rice.Country_Tanzania);
            setCountryShow();
            countrySv.setVisibility(View.GONE);
        } else if (timeZoneId.equalsIgnoreCase(TimeZoneHostEnum_rice.TimeZoneSenegal.getTimeZoneId()) && countries.contains(Constant_rice.WordPrefix + Constant_rice.Suffix_Senegal)) {
            selectCountry(Constant_rice.Country_Senegal);
            setCountryShow();
            countrySv.setVisibility(View.GONE);
        }else {
            selectCountry(Constant_rice.Country_Cote);
            setCountryShow();
            countrySv.setVisibility(View.GONE);
        }


        countrySv.addListItem(countriesName);
        countrySv.setInterceptPickListener(pickStr -> {
            selectCountry(pickStr);
            HttpManager_rice.getInstance().getAppShowInfo();
        });

        //ASAduidManager.getInstance().initAduid();//初始化设备id
        //检查是否已登录
        if (UserInfoHelper_rice.getInstance().didLogin_rice()) {

            countrySv.setInput(UserInfoHelper_rice.getInstance().getCountryName());
            prefix = StaticConfig_rice.getMobilePrefix();
            prefixTv.setText(prefix);
            phoneNumEt.setText(UserInfoHelper_rice.getInstance().getMobil_rice());

            selectCountry(UserInfoHelper_rice.getInstance().getCountryName());

            //查询AppShowInfo
            //HttpManager.getInstance().getAppShowInfo();
        }

        initPrivacyPolicyAndTerm();

        if (UserInfoHelper_rice.getInstance().didLogin_rice() || (!TextUtils.isEmpty(countrySv.getInput())))
            HttpManager_rice.getInstance().getAppShowInfo();

    }

    private void setAgree(boolean agree) {
        isAgree = agree;
        agreementIb.setBackgroundResource(isAgree ? R.drawable.icon_item_check_true:R.drawable.icon_item_check_false);
    }

    private void selectCountry(String countryName){

        StaticConfig_rice.Select_Country = countryName;
        StaticConfig_rice.Country_Word = Constant_rice.WordPrefix + StringUtil_rice.getSafeString(StaticConfig_rice.getCountrySuffix());

        //登录前初始化
        AnalyticsUtil_rice.INSTANCE.initDevice(BaseApplication_rice.gApplication_rice());
        AnalyticsUtil_rice.INSTANCE.saveFirebaseS2SInfo(GlobalConfig_rice.getInstance().getCountryFullPaths());

        StaticConfig_rice.Country_Config = GlobalConfig_rice.getInstance().getCountryConfigTreeMap().get(StaticConfig_rice.Country_Word);
        UserInfoHelper_rice.getInstance().setCountryWord(StaticConfig_rice.Country_Word);
        UserInfoHelper_rice.getInstance().setCountryName(StaticConfig_rice.Select_Country);

        mobileTitleTv.setText(getString(R.string.activity_login_enter_phone_num));

        //登录前初始化
        AnalyticsUtil_rice.INSTANCE.initDevice(BaseApplication_rice.gApplication_rice());

        switch (StaticConfig_rice.Select_Country) {
            case Constant_rice.Country_Senegal://尼日
                privacyPath = Constant_rice.Privacy_Senegal;
                break;
            case Constant_rice.Country_Tanzania://坦桑尼亚
                privacyPath = Constant_rice.Privacy_Tanzania;
                break;
            case Constant_rice.Country_Cote://科特
            default:
                privacyPath = Constant_rice.Privacy_Cote;
        }

    }

    public void onAppShowInfoResponse() {
        setCountryShow();
        if (UserInfoHelper_rice.getInstance().didLogin_rice()) {
            //查询AppShowInfo
            HttpManager_rice.getInstance().requestUserProcess();
        }
    }

    private void setCountryShow(){
        countrySv.setInput(StaticConfig_rice.Select_Country);

        prefix = StaticConfig_rice.getMobilePrefix();
        prefixTv.setText(prefix);

    }

    private void initPrivacyPolicyAndTerm(){

        agreementTv.setText(getString(R.string.accept));
        agreementTv.append(" ");

        SpannableString ss1 = new SpannableString(getString(R.string.privacy_policy));
        ss1.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                HttpManager_rice.getInstance().saveUserBuriedPoint(getClass().getSimpleName()+"_PRIVACY_POLICY_CLICK");
                if (TextUtils.isEmpty(privacyPath)) showToast_rice(getString(R.string.tips_select_country));
                else startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(privacyPath)));
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(true);
                ds.setColor(getColor(R.color.orange_rice));
            }
        },0,ss1.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        agreementTv.append(ss1);

        final String termOfUse = GlobalConfig_rice.getInstance().getTermOfUse();
        if (!TextUtils.isEmpty(termOfUse)){
            agreementTv.append(" ");
            agreementTv.append(getString(R.string.and));
            agreementTv.append(" ");

            SpannableString ss2 = new SpannableString(getString(R.string.terms_of_use));
            ss2.setSpan(new ClickableSpan() {
                @Override
                public void onClick(@NonNull View widget) {
                    HttpManager_rice.getInstance().saveUserBuriedPoint(getClass().getSimpleName()+"_TERM_OF_USE_CLICK");
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(termOfUse)));
                }

                @Override
                public void updateDrawState(@NonNull TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(true);
                    ds.setColor(getColor(R.color.orange_rice));
                }
            },0,ss2.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            agreementTv.append(ss2);
        }

        agreementTv.setMovementMethod(LinkMovementMethod.getInstance());

    }

}